import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
      private DatagramSocket socket = null ;

      private int serverPort = 0;
      private String serverIp = "" ;

      public UdpEchoClient(int serverPort , String serverIp) throws SocketException {
          this.socket = new DatagramSocket();
          this.serverIp = serverIp ;
          this.serverPort = serverPort ;
      }
      public void start() throws IOException {
          System.out.println("客户端启动");

          Scanner scan = new Scanner(System.in);
          while (true){
              System.out.println("输入请求-> ");
              String request = scan.next();
              DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                      request.getBytes().length , InetAddress.getByName(serverIp) ,serverPort );
              socket.send(requestPacket);

              DatagramPacket responsePacket = new DatagramPacket(new byte[4096] , 4096) ;
              socket.receive(responsePacket);
              String response = new String(responsePacket.getData() , 0 , responsePacket.getLength());
              System.out.println("响应:"+response);
          }

      }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient(6060 , "127.0.0.1");
         client.start();
      }


}
